//
//  StockKLineView.m
//  K线图自治
//
//  Created by LK-IOS on 2017/12/13.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "StockKLineView.h"
//K蜡烛视图
#import "StockCandleChartView.h"
#import "StockKLineModel.h"
#import "StockKLineTechBarView.h"
#import "StockKLineMACDView.h"
#import "StockCalculationTool.h"
#import "StockKLineKDJView.h"
#import "StockKLineWRView.h"
#import "StockKlinePriceView.h"
#import "StockKLineQuotaView.h"
#import "StockKlineMANumberView.h"
#import "StockCandleProtocol.h"
#import "UIView+StockViewExtension.h"
#import "UIColor+StockColorEntension.h"
#import "UIBezierPath+StockDraw.h"
#import "StockDataServerTool.h"
#import "StockConst.h"
typedef enum
{
    MACD = 1,
    KDJ,
    WR
}DataLineType;

#define CandleChartScale 0.5
#define TechnicalViewScale 0.05
#define BottomViewScale 0.3
#define MinCount 10
#define MaxCount 30

@interface StockKLineView()<StockCandleProtocol,StockKLineTechBarViewDelegate>


/**
 显示MA数值的View
 */
@property (nonatomic , strong) StockKlineMANumberView *MANumberView;

/**
 顶部详情分栏
 */
@property (nonatomic,strong) StockKLineQuotaView *quotaView;
@property (nonatomic,strong) UIScrollView *scrollView;//最底层滚动的scrollerView
/**
 K线图
 */
@property (nonatomic,strong) StockCandleChartView *candleChartView;

/**
 数据源
 */
@property (nonatomic,strong) NSMutableArray *dataSource;
/**
 K线图包围框
 */
@property (nonatomic,strong) UIView *topBoxView;

/**
 成交量视图包围框
 */
@property (nonatomic , strong) UIView *middleBoxView;

/**
 底部技术图包围框
 */
@property (nonatomic,strong) UIView *bottomBoxView;
/**
 技术图按钮栏
 */
@property (nonatomic,strong) StockKLineTechBarView *technicalView;
/**
 底部盛放 MACD KDJ WR图的view
 */
@property (nonatomic,strong) UIView *bottomView;
@property (nonatomic,assign) DataLineType type;//MACD KDJ DR类型
/**
 MACD
 */
@property (nonatomic,strong) StockKLineMACDView *macdView;
/**
 KDJ
 */
@property (nonatomic,strong) StockKLineKDJView *kdjLineView;
/**
 WR
 */
@property (nonatomic,strong) StockKLineWRView *wrLineView;
/**
 K线价格view
 */
@property (nonatomic,strong) StockKlinePriceView *topPriceView;
/**
 技术图价格View
 */
@property (nonatomic,strong) StockKlinePriceView *bottomPriceView;
//长按手势
@property (nonatomic,strong) UILongPressGestureRecognizer *longPressGesture;
//缩放手势
@property (nonatomic,strong) UIPinchGestureRecognizer *pinchPressGesture;

/**
 加载数据的菊花
 */
@property (nonatomic,strong) UIActivityIndicatorView *activityView;

@property (nonatomic , strong) UIView *boxView;
/**
 手势移动时的纵轴和横轴及中间圆圈
 */
@property (nonatomic,strong) CAShapeLayer *yLayer;
@property (nonatomic,strong) CAShapeLayer *xLayer;
@property (nonatomic,strong) CAShapeLayer *centerLayer;

/**
 长按显示价格的laebl
 */
@property (nonatomic,strong) UILabel *valueLabel;

@end



@implementation StockKLineView

//数据源数组
-(NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

-(instancetype)initWithKLineModels:(NSMutableArray<__kindof StockKLineModel *> *)kLineModels
{
    self = [super init];
    if (self) {
        _dataSource = kLineModels;
        self.backgroundColor = [UIColor whiteColor];
        _type = MACD;//默认显示MACD线
        [self initUI];//初始化界面
        [self addBottomViews];//添加底部的三个技术视图
        
        [self addPriceView];
        [self addActivityView];
        [self addBoxView];
        
    }
    return self;
}

-(void)reDrawWithKLineModelsArray:(NSMutableArray<__kindof StockKLineModel *> *)kLineModels
{
    _dataSource = kLineModels;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reloadData:self.dataSource reload:NO];
    });
}

/**
 初始化界面
 */
- (void)initUI
{
    
    [self addQuotaView];//添加顶部分栏
    
    [self addMANumberView];//添加显示MA数值的View
    
    [self addScrollView];//添加滚动scrollerview
    
    [self addCandleChartView];//添加K线视图
    
    [self addTopBoxView];//添加K线视图外围边框
    
    [self addTechnicalView];//添加技术视图按钮栏
    
    [self addBottomView];//添加技术视图
    
    [self addBottomBoxView];//添加技术视图外围边框
    
    [self addGestureToCandleView];//给K线视图添加手势
}



/**
 添加顶部分栏
 */
- (void)addQuotaView
{
    _quotaView = [StockKLineQuotaView new];
    _quotaView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_quotaView];
    [_quotaView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(64);
        make.left.right.equalTo(self);
        make.height.equalTo(@(64));
    }];
}

/**
 添加显示MA数值的View
 */
-(void)addMANumberView
{
    _MANumberView = [StockKlineMANumberView new];
    _MANumberView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_MANumberView];
    [_MANumberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_quotaView.mas_bottom);
        make.left.equalTo(self).offset(5);
        make.right.equalTo(self).offset(-60);
        make.height.equalTo(@(25));
    }];
}

/**
 K线图上面的ScrollerView
 */
- (void)addScrollView
{
    _scrollView = [UIScrollView new];
    [self addSubview:_scrollView];
    _scrollView.scrollEnabled = YES;
    _scrollView.bounces = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.backgroundColor = [UIColor clearColor];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_MANumberView.mas_bottom);
        make.left.equalTo(self).offset(5);
        make.right.equalTo(self).offset(-60);
        make.height.equalTo(@((LKScreenH - 90)));
    }];
}

/**
 K线图中显示上下蜡烛的view
 */
- (void)addCandleChartView
{
    _candleChartView = [StockCandleChartView new];
    [_scrollView addSubview:_candleChartView];
    _candleChartView.delegate = self;
    
    [_candleChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_scrollView);
        make.right.equalTo(_scrollView);
        make.height.equalTo(@((LKScreenH - 90)*CandleChartScale));
        make.top.equalTo(_scrollView);
    }];
}

/**
添加K线视图外围边框
 */
- (void)addTopBoxView
{
    _topBoxView = [UIView new];
    [self addSubview:_topBoxView];
    _topBoxView.userInteractionEnabled = NO;
    _topBoxView.layer.borderWidth = 1;
    _topBoxView.layer.borderColor = [UIColor Stock_TextColor].CGColor;
    [_topBoxView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrollView.mas_top).offset(1);
        make.left.equalTo(_scrollView.mas_left).offset(-1);
        make.right.equalTo(_scrollView.mas_right).offset(1);
        make.height.equalTo(@((LKScreenH - 90)*CandleChartScale));
    }];
}


/**
添加技术视图按钮栏
 */
- (void)addTechnicalView
{
    _technicalView = [StockKLineTechBarView new];
    [self addSubview:_technicalView];
    _technicalView.delagate = self;
    
    [_technicalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_topBoxView.mas_bottom).offset(1);
        make.left.right.equalTo(_scrollView);
        make.height.equalTo(@((LKScreenH-90)*TechnicalViewScale));
    }];
    
    [_technicalView.macdButton setTitle:@"MACD" forState:UIControlStateNormal];
    [_technicalView.wrButton setTitle:@"WR" forState:UIControlStateNormal];
    [_technicalView.kdjButton setTitle:@"KDJ" forState:UIControlStateNormal];
}

/**
 底部成交量视图及技术数据显示视图
 */
- (void)addBottomView
{
    _bottomView = [UIView new];
    [_scrollView addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_technicalView.mas_bottom).offset(1);
        make.left.right.equalTo(_candleChartView);
        make.height.equalTo(@((LKScreenH- 90)*BottomViewScale));
    }];
    [_bottomView layoutIfNeeded];
}

/**
 底部技术视图的盒子视图
 */
- (void)addBottomBoxView
{
    _bottomBoxView = [UIView new];
    [self addSubview:_bottomBoxView];
    _bottomBoxView.userInteractionEnabled = NO;
    _bottomBoxView.layer.borderWidth = 1;
    _bottomBoxView.layer.borderColor = [UIColor Stock_TextColor].CGColor;
    [_bottomBoxView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_bottomView.mas_top);
        make.left.equalTo(_scrollView.mas_left).offset(-1);
        make.right.equalTo(_scrollView.mas_right).offset(1);
        make.height.equalTo(@((LKScreenH - 90)*BottomViewScale));
    }];
    
}

/**
 给K线视图添加手势
 */
- (void)addGestureToCandleView
{
    _longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGesture:)];
    [self.candleChartView addGestureRecognizer:_longPressGesture];
    
    _pinchPressGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGesture:)];
    [self.scrollView addGestureRecognizer:_pinchPressGesture];
}

/**
 加载更多数据的时候显示的菊花
 */
- (void)addActivityView
{
    _activityView = [UIActivityIndicatorView new];
    [self addSubview:_activityView];
    _activityView.hidesWhenStopped = YES;
    _activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [_activityView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(5));
        make.centerY.equalTo(_candleChartView);
        make.size.mas_equalTo(CGSizeMake(15, 15));
    }];
}


/**
 添加技术视图的三个视图   MACD  KDJ  WR
 */
- (void)addBottomViews
{
    //MACD  View
    _macdView = [StockKLineMACDView new];
    [_bottomView addSubview:_macdView];
    _macdView.lineWidth = 1;
    [_macdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_bottomView);
        make.left.right.equalTo(_bottomView);
    }];
    //KDJ view
    _kdjLineView = [StockKLineKDJView new];
    [_bottomView addSubview:_kdjLineView];
    _kdjLineView.lineWidth = 1;
    [_kdjLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_bottomView);
        make.left.right.equalTo(_bottomView);
    }];
    _kdjLineView.hidden = YES;
    
    //WR   view
    _wrLineView = [StockKLineWRView new];
    [_bottomView addSubview:_wrLineView];
    _wrLineView.lineWidth = 1;
    [_wrLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_bottomView);
        make.left.right.equalTo(_bottomView);
    }];
    _wrLineView.hidden = YES;
}

/**
 添加显示价格的视图
 */
- (void)addPriceView
{
    _topPriceView = [StockKlinePriceView new];
    [self addSubview:_topPriceView];
    
    [_topPriceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_topBoxView);
        make.right.equalTo(self);
        make.left.equalTo(_topBoxView.mas_right);
    }];
    
    _bottomPriceView = [StockKlinePriceView new];
    [self addSubview:_bottomPriceView];
    
    [_bottomPriceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_bottomBoxView);
        make.right.equalTo(self);
        make.left.equalTo(_bottomBoxView.mas_right);
    }];
}

/**
 添加手势移动时的边框
 */
-(void)addBoxView
{
    _boxView = [UIView new];
    [self insertSubview:_boxView aboveSubview:self.scrollView];
    _boxView.userInteractionEnabled = NO;
    _boxView.backgroundColor = [UIColor clearColor];
    [_boxView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(_topBoxView);
        make.bottom.equalTo(_bottomBoxView.mas_bottom);
    }];
    //点按手势的十字线
    [self initCrossLine];
}

/**
 点按手势的十字线
 */
- (void)initCrossLine
{
    //手势移动时，显示的横线
    self.xLayer = [CAShapeLayer layer];
    self.xLayer.lineWidth = TimeLineLineWidth;
    self.xLayer.lineCap = kCALineCapRound;
    self.xLayer.lineJoin = kCALineJoinRound;
    self.xLayer.strokeColor = [UIColor Stock_GesTureLineColor].CGColor;
    self.xLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.xLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:2],nil]];
    [self.boxView.layer addSublayer:self.xLayer];
    
    //手势移动时，显示的纵线
    self.yLayer = [CAShapeLayer layer];
    self.yLayer.lineWidth = TimeLineLineWidth;
    self.yLayer.lineCap = kCALineCapRound;
    self.yLayer.lineJoin = kCALineJoinRound;
    self.yLayer.strokeColor = [UIColor Stock_GesTureLineColor].CGColor;
    self.yLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.yLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:2],nil]];
    [self.boxView.layer addSublayer:self.yLayer ];
    

    //手势移动时随手势中信点移动的圆圈
    self.centerLayer = [CAShapeLayer layer];
    UIBezierPath *centerPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:cycleRate - 2 startAngle:0 endAngle:2*M_PI clockwise:YES];
    self.centerLayer.path = centerPath.CGPath;
    self.centerLayer.lineWidth = TimeLineLineWidth;
    self.centerLayer.lineCap = kCALineCapRound;
    self.centerLayer.lineJoin = kCALineJoinRound;
    self.centerLayer.strokeColor = [UIColor Stcok_TimeCycleFillColor].CGColor;
    self.centerLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.boxView.layer addSublayer:self.centerLayer];
    self.centerLayer.hidden = YES;
    
    //涨跌幅度
    _valueLabel = [self createLabel];
    [self.boxView addSubview:_valueLabel];
    self.valueLabel.text = @"---";
    _valueLabel.frame = CGRectMake(0, 0, 100, 20);
}


/**
 指标切换代理
 */
- (void)didSelectButton:(UIButton *)button index:(NSInteger)index
{
    if (index == 1)
    {
        _type = MACD;
    }
    
    else if (index == 2)
    {
        _type = WR;
    }
    
    else
    {
        _type = KDJ;
    }
    
    [self showIndexLineView:self.candleChartView.leftPostion startIndex:self.candleChartView.currentStartIndex count:self.candleChartView.displayCount];
}

/**
 长按手势
 */
- (void)longGesture:(UILongPressGestureRecognizer*)longPress
{
    static CGFloat oldPositionX = 0;
    if(UIGestureRecognizerStateChanged == longPress.state || UIGestureRecognizerStateBegan == longPress.state)
    {
    
        CGPoint location = [longPress locationInView:self.candleChartView];
        if(ABS(oldPositionX - location.x) < (self.candleChartView.candleWidth + self.candleChartView.candleSpace)/2)
        {
            return;
        }
        
        self.scrollView.scrollEnabled = NO;
        oldPositionX = location.x;
        
        CGPoint point = [self.candleChartView getLongPressModelPostionWithXPostion:location.x];
        CGFloat xPositoin = point.x + (self.candleChartView.candleWidth)/2.f - self.candleChartView.candleSpace/2.f ;
        CGFloat yPositoin = point.y +_candleChartView.topMargin;
        
        //坐标转换，将scrollerview上面的点转换到BoxView上面
        CGPoint positionPoint = [_boxView convertPoint:CGPointMake(xPositoin, yPositoin) fromView:self.scrollView];

        //手势移动时，变更指示线位置
        
        self.centerLayer.hidden = NO;
        
        UIBezierPath *centerPath = [UIBezierPath bezierPathWithArcCenter:positionPoint radius:cycleRate startAngle:0 endAngle:2*M_PI clockwise:YES];
        self.centerLayer.path = centerPath.CGPath;
        
        UIBezierPath *xPath = [UIBezierPath bezierPath];
        [xPath moveToPoint:CGPointMake(positionPoint.x,0)];
        [xPath addLineToPoint:CGPointMake(positionPoint.x,self.boxView.height)];
        self.xLayer.path = xPath.CGPath;
        
        //移动时的横轴是绘制在scrollview上面的，所以要取scrollview尺寸
        UIBezierPath *yPath = [UIBezierPath bezierPath];
        [yPath moveToPoint:CGPointMake(0,positionPoint.y)];
        [yPath addLineToPoint:CGPointMake(self.boxView.width,positionPoint.y)];
        self.yLayer.path = yPath.CGPath;
        
        self.valueLabel.hidden = NO;
        self.valueLabel.x = self.boxView.width - self.valueLabel.width;
        self.valueLabel.centerY = positionPoint.y;
        
        [_quotaView layoutIfNeeded];
        
    }
    
    if(longPress.state == UIGestureRecognizerStateEnded)
    {
        self.valueLabel.hidden = YES;
        self.xLayer.path = [UIBezierPath bezierPath].CGPath;
        self.yLayer.path = [UIBezierPath bezierPath].CGPath;
        self.centerLayer.path = [UIBezierPath bezierPath].CGPath;
        
        oldPositionX = 0;
        self.scrollView.scrollEnabled = YES;
    }
}

/**
缩放手势
 */
- (void)pinchGesture:(UIPinchGestureRecognizer*)pinchPress
{
    if (pinchPress.numberOfTouches < 2)
    {
        _candleChartView.kvoEnable = YES;
        _scrollView.scrollEnabled = YES;
        return;
    }
    
    switch (pinchPress.state) {
        case UIGestureRecognizerStateBegan:
        {
            _scrollView.scrollEnabled = NO;
            _candleChartView.kvoEnable = NO;
        }break;
        case UIGestureRecognizerStateEnded:
        {
            _scrollView.scrollEnabled = YES;
            _candleChartView.kvoEnable = YES;
        }break;
        default:
            break;
    }
    
    CGFloat scale = pinchPress.scale;
    CGFloat originScale= 1.0;
    CGFloat minScale = 0.04;
    NSInteger displayCount = self.candleChartView.displayCount;
    CGFloat diffScale = scale - originScale;
    
    if (fabs(diffScale) > minScale)
    {
        CGPoint point1 = [pinchPress locationOfTouch:0 inView:self.scrollView];
        CGPoint point2 = [pinchPress locationOfTouch:1 inView:self.scrollView];
        CGFloat pinCenterX = (point1.x + point2.x) / 2;
        CGFloat scrollViewPinCenterX =  pinCenterX;
        NSInteger pinCenterLeftCount = scrollViewPinCenterX / (_candleChartView.candleWidth + _candleChartView.candleSpace);
        pinCenterLeftCount = _candleChartView.currentStartIndex;
        CGFloat newDisplayCount = diffScale > 0 ? (displayCount - 1) : (1 + displayCount);
        
        if (newDisplayCount+pinCenterLeftCount > _candleChartView.dataArray.count)
        {
            newDisplayCount = _candleChartView.dataArray.count - pinCenterLeftCount;
        }
        
        if (newDisplayCount < MinCount && scale >=1)
        {
            newDisplayCount = MinCount;
        }
        
        if (newDisplayCount > MaxCount && scale < 1)
        {
            newDisplayCount = MaxCount;
        }
        
        _candleChartView.displayCount = (NSInteger)newDisplayCount;
        [_candleChartView calcuteCandleWidth];
        [_candleChartView updateWidth];
        
        CGFloat newPinCenterX = pinCenterLeftCount * _candleChartView.candleWidth + (pinCenterLeftCount) * _candleChartView.candleSpace;
        CGFloat newOffsetX = newPinCenterX;
        _scrollView.contentOffset = CGPointMake(newOffsetX > 0 ? newOffsetX : 0, 0);
        _candleChartView.contentOffset = _scrollView.contentOffset.x;
        [_candleChartView drawKLine];
    }
}

/**
K线图代理协议方法
 */
-(void)displayLastModel:(StockKLineModel *)kLineModel andMALinesNUmberArray:(NSMutableArray *)linesNumberArray
{
    _quotaView.model = kLineModel;
    
    _MANumberView.malinesArray = linesNumberArray;
    [_MANumberView setNeedsDisplay];
}


/**
 
 长按手势获得当前k线下标以及模型 及MA数据
 @param kLineModeIndex 当前k线在可视范围数组的位置下标
 @param kLineModel k线模型
 @param linesNumberArray MA数据
 */
-(void)longPressCandleViewWithIndex:(NSInteger)kLineModeIndex kLineModel:(StockKLineModel *)kLineModel andMALinesNUmberArray:(NSMutableArray *)linesNumberArray
{
    _quotaView.model = kLineModel;
    
    //显示价格laebl
    NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:[UIColor Stock_GesTureLabelBackColor]};
    NSString *priceString;
    if ([kLineModel.priceUpDownRate floatValue] >0) {
        self.valueLabel.textColor = [UIColor Stock_PriceUpColor];
        priceString = [NSString stringWithFormat:@"%@" , kLineModel.Low];
    }else{
        self.valueLabel.textColor = [UIColor Stock_PriceDownColor];
        priceString = [NSString stringWithFormat:@"%@" , kLineModel.High];
    }
    CGRect valueLabelRect = [self rectOfNSString:priceString attribute:attribute];
    self.valueLabel.frame = CGRectMake(0, 0, valueLabelRect.size.width, valueLabelRect.size.height);
    
    self.valueLabel.text = priceString;
    
    
    _MANumberView.malinesArray = linesNumberArray;
    [_MANumberView setNeedsDisplay];
    
    
}

- (void)displayScreenleftPostion:(CGFloat)leftPostion startIndex:(NSInteger)index count:(NSInteger)count
{
    [self showIndexLineView:leftPostion startIndex:index count:count];
}

- (void)showIndexLineView:(CGFloat)leftPostion startIndex:(NSInteger)index count:(NSInteger)count
{
    _topPriceView.maxPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.candleChartView.maxY];
    _topPriceView.middlePriceLabel.text = [NSString stringWithFormat:@"%.2f",(self.candleChartView.maxY - self.candleChartView.minY)/2 + self.candleChartView.minY];
    _topPriceView.minPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.candleChartView.minY];
    
    if (_type == MACD)
    {
        [_kdjLineView setHidden:YES];
        [_wrLineView setHidden:YES];
        [_macdView setHidden:NO];
        _macdView.candleSpace = _candleChartView.candleSpace;
        _macdView.candleWidth = _candleChartView.candleWidth;
        _macdView.leftPostion = leftPostion;
        _macdView.startIndex = index;
        _macdView.displayCount = count;
        [_macdView stockFill];
        
        _bottomPriceView.maxPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.macdView.maxY];
        _bottomPriceView.middlePriceLabel.text = [NSString stringWithFormat:@"%.2f",(self.macdView.maxY - self.macdView.minY)/2 + self.macdView.minY];
        _bottomPriceView.minPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.macdView.minY];
    }
    
    else  if (_type == WR)
    {
        [_kdjLineView setHidden:YES];
        [_macdView setHidden:YES];
        [_wrLineView setHidden:NO];
        _wrLineView.candleSpace = _candleChartView.candleSpace;
        _wrLineView.candleWidth = _candleChartView.candleWidth;
        _wrLineView.leftPostion = leftPostion;
        _wrLineView.startIndex = index;
        _wrLineView.displayCount = count;
        [_wrLineView stockFill];
        
        _bottomPriceView.maxPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.wrLineView.maxY];
        _bottomPriceView.middlePriceLabel.text = [NSString stringWithFormat:@"%.2f",(self.wrLineView.maxY - self.wrLineView.minY)/2 + self.wrLineView.minY];
        _bottomPriceView.minPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.wrLineView.minY];
    }
    
    else if(_type == KDJ)
    {
        [_kdjLineView setHidden:NO];
        [_macdView setHidden:YES];
        [_wrLineView setHidden:YES];
        _kdjLineView.candleSpace = _candleChartView.candleSpace;
        _kdjLineView.candleWidth = _candleChartView.candleWidth;
        _kdjLineView.leftPostion = leftPostion;
        _kdjLineView.startIndex = index;
        _kdjLineView.displayCount = count;
        [_kdjLineView stockFill];
        
        _bottomPriceView.maxPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.kdjLineView.maxY];
        _bottomPriceView.middlePriceLabel.text = [NSString stringWithFormat:@"%.2f",(self.kdjLineView.maxY - self.kdjLineView.minY)/2 + self.kdjLineView.minY];
        _bottomPriceView.minPriceLabel.text = [NSString stringWithFormat:@"%.2f",self.kdjLineView.minY];
    }
}


/**
 K线图加载更多数据的代理方法
 */
- (void)displayMoreDataWithLastDataModel:(StockKLineModel *)model
{
    [_activityView startAnimating];
    __weak typeof(self) weakSelf = self;
    
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0* NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [weakSelf loadMoreData];
    });
}

- (void)loadMoreData
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(stockKLineView:LoadmoreData:)]) {
        NSMutableArray *moreData = [self.delegate stockKLineView:self LoadmoreData:@""];
        if (moreData.count) {
            NSMutableArray *tempArray = _candleChartView.dataArray.mutableCopy;
            for (NSInteger i = 0; i < moreData.count; i++) {
                StockKLineModel *model = moreData[i];
                [tempArray addObject:model];
            }
            [self reloadData:tempArray reload:YES];
            
            [_activityView stopAnimating];
        }else{
            [_activityView stopAnimating];
        }

    }
}

/**
 K线数据刷新
 @param array 数据数组
 @param reload 是刷新还是加载
 */
- (void)reloadData:(NSMutableArray*)array reload:(BOOL)reload
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        
        _macdView.dataArray = computeMACDData(array).mutableCopy;
        _kdjLineView.dataArray = computeKDJData(array).mutableCopy;
        _wrLineView.dataArray = computeWRData(array,10).mutableCopy;
        
        self.candleChartView.dataArray = array;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (reload)
            {
                [self.candleChartView reload];
            }
            
            else
            {
                [self.candleChartView stockFill];
            }
        });
    });
}



/**
 创建长按时显示的LABEL

 @return UILABEL
 */
- (UILabel*)createLabel
{
    UILabel *label = [UILabel new];
    label.backgroundColor = [UIColor Stock_GesTureLabelBackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor Stock_TextColor];
    label.hidden = YES;
    label.font = [UIFont systemFontOfSize:12];
    return label;
}

/**
 计算一个字段的宽高
 */
- (CGRect)rectOfNSString:(NSString *)string attribute:(NSDictionary *)attribute
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 0)
                                       options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil];
    return rect;
}

@end

